﻿using System.Text;

namespace CocoaAni.Net.WebSockets.Tools;

public class WSHttpHeadersHandler
{
    public Dictionary<string, object> Headers { get; set; } = new Dictionary<string, object>();

    public string? GetHeaderValue(string name)
    {
        var headerValues = GetHeaderValues(name);
        if (headerValues == null)
        {
            return null;
        }
        var sb = new StringBuilder();
        foreach (var headerValue in headerValues)
        {
            sb.Append($"{headerValue}; ");
        }

        return sb.ToString(0, sb.Length - 2);
    }

    public string GetHeaderValue(string name, string defaultValue) => GetHeaderValue(name) ?? defaultValue;

    public IEnumerable<string>? GetHeaderValues(string name)
    {
        if (!Headers.ContainsKey(name))
        {
            return null;
        }
        var obj = Headers[name];
        return obj switch
        {
            string strValue
                => Enumerable.Repeat(strValue, 1),
            List<string> listValue
                => listValue,
            _
                => null
        };
    }

    public void SetHeaderValues(string name, IEnumerable<string> values) => Headers[name] = values;

    public void SetHeaderValue(string name, string? value)
    {
        if (value == null)
        {
            Headers.Remove(name);
            return;
        }
        Headers[name] = value;
    }

    public void AddHeaderValue(string name, string value)
    {
        if (!Headers.ContainsKey(name))
        {
            Headers[name] = value;
            return;
        }
        var obj = Headers[name];
        switch (obj)
        {
            case List<string> valueList:
                valueList.Add(value);
                break;

            case string strValue:
                Headers[name] = new List<string>()
                {
                    strValue, value
                };
                break;
        }
    }

    public void AddHeaderValues(string name, IEnumerable<string> values)
    {
        if (!Headers.ContainsKey(name))
        {
            Headers[name] = new List<string>(values);
        }
        else
        {
            var obj = Headers[name];
            switch (obj)
            {
                case string strValue:
                    {
                        var list = new List<string> { strValue };
                        list.AddRange(values);
                        Headers[name] = list;
                        break;
                    }
                case List<string> list:
                    list.AddRange(values);
                    break;
            }
        }
    }
}